/*
 * Course.cpp
 *
 *  Created on: 01/06/2011
 *      Author: dela
 */

#include "Course.h"
#include <string.h>

using namespace std;

/**
 *
 */
char* Course::toBuffer( int *size ) {
	*size = 0;
	*size += sizeof(unsigned long);
	*size += name.size();
	*size += sizeof(bool);
	*size += password.size();
	*size += description.size();
	*size += startDate.size();
	*size += duration.size();
	*size += 20;

	int auxSize = 0;
	int offset = 0;
	char *buff = new char[*size];

	//id
	memcpy(buff, &id , sizeof(unsigned long));
	offset += sizeof(unsigned long);

	//name
	auxSize = name.size();
	memcpy(buff+offset, &auxSize, 4);
	offset += 4;
	memcpy(buff+offset, name.c_str(), auxSize);
	offset += auxSize;

	//hasPassword
	memcpy(buff+offset, &hasPassword, sizeof(bool));
	offset += sizeof(bool);

	//password
	auxSize = password.size();
	memcpy(buff+offset, &auxSize, 4);
	offset += 4;
	memcpy(buff+offset, password.c_str(), auxSize);
	offset += auxSize;

	//description
	auxSize = description.size();
	memcpy(buff+offset, &auxSize, 4);
	offset += 4;
	memcpy(buff+offset, description.c_str(), auxSize);
	offset += auxSize;

	//startDate
	auxSize = startDate.size();
	memcpy(buff+offset, &auxSize, 4);
	offset += 4;
	memcpy(buff+offset, startDate.c_str(), auxSize);
	offset += auxSize;

	//duration
	auxSize = duration.size();
	memcpy(buff+offset, &auxSize, 4);
	offset += 4;
	memcpy(buff+offset, duration.c_str(), auxSize);

	return buff;
}

/**
 *
 */
Course::Course( char *buff ) {
	int auxSize = 0;
	int offset = 0;

	//id
	this->id = *((unsigned long*) buff);
	offset += sizeof(unsigned long);

	//name
	auxSize = (int) *(buff+offset);
	offset += 4;
	this->name.append(buff+offset, auxSize);
	offset += auxSize;

	//hasPassword
	this->hasPassword = (bool) *(buff+offset);
	offset += sizeof(bool);

	//password
	auxSize = (int) *(buff+offset);
	offset += 4;
	this->password.append(buff+offset, auxSize);
	offset += auxSize;

	//description
	auxSize = (int) *(buff+offset);
	offset += 4;
	this->description.append(buff+offset, auxSize);
	offset += auxSize;

	//startDate
	auxSize = (int) *(buff+offset);
	offset += 4;
	this->startDate.append(buff+offset, auxSize);
	offset += auxSize;

	//duration
	auxSize = (int) *(buff+offset);
	offset += 4;
	this->duration.append(buff+offset, auxSize);
}
